package com.fishingwithme.android.ui.screens.harvest

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import com.fishingwithme.android.R
import com.fishingwithme.android.data.model.ApproveRuleItem
import com.fishingwithme.android.data.model.City
import com.fishingwithme.android.navigation.FishingNavigation
import com.fishingwithme.android.ui.components.MultiImageDisplay
import com.fishingwithme.android.ui.screens.anybitting.SwitchHandler
import com.fishingwithme.android.ui.screens.map.SideBar
import com.fishingwithme.android.ui.screens.map.SideBarItem
import com.fishingwithme.android.ui.theme.AppDimensions
import com.fishingwithme.android.ui.viewmodels.AuditViewModel
import com.fishingwithme.android.ui.viewmodels.HarvestShowViewModel
import kotlinx.coroutines.launch

@OptIn(ExperimentalLayoutApi::class, ExperimentalMaterial3Api::class)
@Composable
fun HarvestApproveScreen(
    navController: NavController,
    harvestId: String,
    viewModel: HarvestShowViewModel = hiltViewModel(),
    auditViewModel: AuditViewModel = hiltViewModel()  // Add AuditViewModel for approval
) {
    // Load harvest details when the screen is created
    LaunchedEffect(harvestId) {
        if (harvestId.isNotEmpty()) {
            viewModel.loadApproveHarvest(harvestId)
        }
    }

    val uiState by viewModel.uiState.collectAsState()

    // State for approval bottom sheet
    var showApprovalSheet by remember { mutableStateOf(false) }
    val selectedCities = remember { mutableStateListOf<City>() }
    var isApproved by remember { mutableStateOf(true) }
    var searchQuery by remember { mutableStateOf("") }
    val searchResults = remember { mutableStateListOf<City>() }
    var isSearching by remember { mutableStateOf(false) }
    var selectedReason by remember { mutableStateOf<ApproveRuleItem?>(null) }

    val baseBarItems by remember {
        mutableStateOf(
            mutableListOf(
                SideBarItem(
                    key = "go_spot",
                    icon = R.mipmap.navi,
                    handler = SwitchHandler("go_spot", R.mipmap.navi)
                ),
                SideBarItem(
                    key = "approve",
                    icon = R.mipmap.approve,
                    handler = SwitchHandler("approve", R.mipmap.approve)
                )
            )
        )
    }

    // Approval Bottom Sheet
    if (showApprovalSheet) {
        val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
        val coroutineScope = rememberCoroutineScope()

        ModalBottomSheet(
            onDismissRequest = { showApprovalSheet = false },
            sheetState = sheetState,
            modifier = Modifier.fillMaxHeight()
        ) {
            HarvestApprovalContent(
                selectedCities = selectedCities,
                isApproved = isApproved,
                searchQuery = searchQuery,
                searchResults = searchResults,
                isSearching = isSearching,
                onSearchQueryChange = { query ->
                    searchQuery = query
                    // Call the ViewModel's searchCities method
                    if (query.isNotEmpty()) {
                        isSearching = true
                        viewModel.searchCities(query) { cities ->
                            searchResults.clear()
                            searchResults.addAll(cities)
                            isSearching = false
                        }
                    } else {
                        searchResults.clear()
                    }
                },
                onCitySelected = { city ->
                    if (!selectedCities.contains(city)) {
                        selectedCities.add(city)
                    }
                },
                onCityRemoved = { city ->
                    selectedCities.remove(city)
                },
                onApprovalChanged = { isApproved = it },
                onSubmit = { ruleItemId, reason ->
                    // Handle submission logic here using AuditViewModel
                    val harvestIdValue =
                        harvestId.toLongOrNull() // Use the harvestId parameter passed to the screen
                    if (harvestIdValue != null) {
                        val channels = selectedCities.map { it.cityCode }

                        auditViewModel.auditHarvest(
                            bizId = harvestIdValue,
                            ruleItemId = ruleItemId,
                            reason = reason,
                            state = isApproved,
                            channels = channels,
                            onSuccess = {
                                // Handle success - maybe show a toast or notification
                                coroutineScope.launch {
                                    sheetState.hide()
                                }.invokeOnCompletion {
                                    showApprovalSheet = false
                                }
                            },
                            onError = { errorMessage ->
                                // Handle error - maybe show a toast or error message
                                println("Audit failed: $errorMessage")
                            }
                        )
                    } else {
                        // Handle invalid harvest ID
                        coroutineScope.launch {
                            sheetState.hide()
                        }.invokeOnCompletion {
                            showApprovalSheet = false
                        }
                    }
                },
                onCancel = {
                    coroutineScope.launch {
                        sheetState.hide()
                    }.invokeOnCompletion {
                        showApprovalSheet = false
                    }
                },
                rulesItems = viewModel.uiState.value.rulesItems,
                isRulesLoading = viewModel.uiState.value.isRulesLoading,
                onLoadRulesItems = { viewModel.loadRulesItems(2) }, // 2 for harvest rules
                selectedReason = selectedReason,
                onReasonSelected = { reason -> selectedReason = reason }
            )
        }
    }

    Scaffold(
    ) { paddingValues ->
        SideBar(
            barItems = baseBarItems, onItemClick = { handler ->
                var router: String? = null
                if (handler.key == "go_spot") {
                    router = "${FishingNavigation.HOME}?id=${uiState.spotId}"
                } else if (handler.key == "approve") {
                    // Show the approval bottom sheet
                    showApprovalSheet = true
                }
                if (router != null) {
                    navController.navigate(router)
                }

            })
        LazyColumn(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
                .padding(AppDimensions.SPACING_2),
            verticalArrangement = Arrangement.spacedBy(AppDimensions.SPACING_2)
        ) {
            // Loading indicator
            if (uiState.isLoading) {
                item {
                    Card(
                        modifier = Modifier.fillMaxWidth(),
                        shape = RoundedCornerShape(
                            AppDimensions.ROUNDED_CORNER_4
                        ),
                    ) {
                        Column(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(AppDimensions.SPACING_2),
                            horizontalAlignment = Alignment.CenterHorizontally
                        ) {
                            Text(
                                text = "加载中...", style = MaterialTheme.typography.bodyLarge
                            )
                        }
                    }
                }
            }

            // Error message
            uiState.error?.let { errorMessage ->
                item {
                    Card(
                        modifier = Modifier.fillMaxWidth(), colors = CardDefaults.cardColors(
                            containerColor = MaterialTheme.colorScheme.errorContainer
                        )
                    ) {
                        Column(modifier = Modifier.padding(AppDimensions.SPACING_16)) {
                            Text(
                                text = errorMessage,
                                color = MaterialTheme.colorScheme.onErrorContainer,
                                style = MaterialTheme.typography.bodyMedium
                            )
                        }
                    }
                }
            }

            // Images gallery
            if (uiState.images.isNotEmpty()) {
                item {
                    Card(modifier = Modifier.fillMaxWidth()) {
                        Column(modifier = Modifier.padding(AppDimensions.SPACING_16)) {
                            MultiImageDisplay(
                                pictures = uiState.images, modifier = Modifier.fillMaxWidth()
                            )
                        }
                    }
                }
            }

            // Harvest type
            if (uiState.harvestType.isNotEmpty()) {
                item {
                    Card(modifier = Modifier.fillMaxWidth()) {
                        Column(modifier = Modifier.padding(AppDimensions.SPACING_16)) {
                            Text(
                                text = "类型:",
                                style = MaterialTheme.typography.titleMedium,
                                modifier = Modifier.padding(bottom = AppDimensions.SPACING_8)
                            )

                            Text(
                                text = uiState.harvestType,
                                style = MaterialTheme.typography.bodyLarge
                            )
                        }
                    }
                }
            }

            // Score
            if (uiState.score.isNotEmpty()) {
                item {
                    Card(modifier = Modifier.fillMaxWidth()) {
                        Column(modifier = Modifier.padding(AppDimensions.SPACING_16)) {
                            Text(
                                text = "评分:",
                                style = MaterialTheme.typography.titleMedium,
                                modifier = Modifier.padding(bottom = AppDimensions.SPACING_8)
                            )

                            Text(
                                text = uiState.score, style = MaterialTheme.typography.bodyLarge
                            )
                        }
                    }
                }
            }

            // Recommend status
            item {
                Card(modifier = Modifier.fillMaxWidth()) {
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(AppDimensions.SPACING_16),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Text(
                            text = if (uiState.isRec) "已推荐" else "未推荐",
                            style = MaterialTheme.typography.bodyLarge
                        )
                    }
                }
            }

            // Fish types
            if (uiState.fishTypes.isNotEmpty()) {
                item {
                    Card(modifier = Modifier.fillMaxWidth()) {
                        Column(modifier = Modifier.padding(AppDimensions.SPACING_16)) {
                            Text(
                                text = "渔获种类",
                                style = MaterialTheme.typography.titleMedium,
                                modifier = Modifier.padding(bottom = AppDimensions.SPACING_8)
                            )

                            FlowRow(
                                modifier = Modifier.fillMaxWidth(),
                                horizontalArrangement = Arrangement.spacedBy(AppDimensions.SPACING_8)
                            ) {
                                uiState.fishTypes.forEach { fish ->
                                    Card(
                                        modifier = Modifier.padding(AppDimensions.SPACING_4),
                                        colors = CardDefaults.cardColors(
                                            containerColor = MaterialTheme.colorScheme.secondaryContainer
                                        )
                                    ) {
                                        Text(
                                            text = fish,
                                            style = MaterialTheme.typography.bodySmall,
                                            modifier = Modifier.padding(AppDimensions.SPACING_8)
                                        )
                                    }
                                }
                            }
                        }
                    }
                }
            }

            // Comment/description
            if (uiState.comment.isNotEmpty()) {
                item {
                    Card(modifier = Modifier.fillMaxWidth()) {
                        Column(modifier = Modifier.padding(AppDimensions.SPACING_16)) {
                            Text(
                                text = "描述:",
                                style = MaterialTheme.typography.titleMedium,
                                modifier = Modifier.padding(bottom = AppDimensions.SPACING_8)
                            )

                            Text(
                                text = uiState.comment, style = MaterialTheme.typography.bodyLarge
                            )
                        }
                    }
                }
            }

        }
    }
}